namespace Skymate.Mvc.Controllers.Dynamic.Scripting.Angular
{
    using System.Text;

    using Skymate.Mvc.Controllers.Dynamic;
    using Skymate.Mvc.Controllers.Dynamic.Scripting;

    internal class AngularProxyGenerator : IScriptProxyGenerator
    {
        private readonly DynamicApiControllerInfo _controllerInfo;

        public AngularProxyGenerator(DynamicApiControllerInfo controllerInfo)
        {
            this._controllerInfo = controllerInfo;
        }

        public string Generate()
        {
            var script = new StringBuilder();

            /*app.core*/


            script.AppendLine("(function () {");
            script.AppendLine("");
            /*script.AppendLine("    if (!angular) {");
            script.AppendLine("        return;");
            script.AppendLine("    }");*/
            script.AppendLine("    ");
            script.AppendLine("    var appcore = angular.module('app.core');");
            script.AppendLine("    ");
            script.AppendLine("    appcore.factory('abp.services." + this._controllerInfo.ServiceName.Replace("/", ".") + "', [");
            script.AppendLine("        '$http', function ($http) {");
            script.AppendLine("            return new function () {");

            foreach (var methodInfo in this._controllerInfo.Actions.Values)
            {
                var actionWriter = new AngularActionScriptWriter(this._controllerInfo, methodInfo);
                actionWriter.WriteTo(script);
            }

            script.AppendLine("            };");
            script.AppendLine("        }");
            script.AppendLine("    ]);");
            script.AppendLine();

            script.AppendLine();
            script.AppendLine("})();");

            return script.ToString();
        }
    }
}